import {
  Role,
  Permission,
  CreateRoleRequest,
  UpdateRoleRequest,
  PaginatedResponse,
  ApiResponse,
} from '@/types';

// 角色服务类
class RoleService {
  private baseUrl = '/api/roles';

  // 获取角色列表
  async getRoles(params: any = {}): Promise<PaginatedResponse<Role>> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    const response = await fetch(`${this.baseUrl}?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch roles: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取单个角色详情
  async getRole(id: string): Promise<ApiResponse<Role>> {
    const response = await fetch(`${this.baseUrl}/${id}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch role: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 创建角色
  async createRole(data: CreateRoleRequest): Promise<ApiResponse<Role>> {
    const response = await fetch(this.baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to create role: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 更新角色
  async updateRole(id: string, data: UpdateRoleRequest): Promise<ApiResponse<Role>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to update role: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 删除角色
  async deleteRole(id: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'DELETE',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to delete role: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 批量删除角色
  async batchDeleteRoles(ids: string[]): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/batch`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ids }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to batch delete roles: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 更新角色权限
  async updateRolePermissions(id: string, permissions: string[]): Promise<ApiResponse<Role>> {
    const response = await fetch(`${this.baseUrl}/${id}/permissions`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ permissions }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to update role permissions: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取权限列表
  async getPermissions(): Promise<Permission[]> {
    const response = await fetch('/api/permissions');
    if (!response.ok) {
      throw new Error(`Failed to fetch permissions: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 分配角色给用户
  async assignRoleToUsers(roleId: string, userIds: string[]): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${roleId}/assign`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userIds }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to assign role: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 移除用户角色
  async removeRoleFromUsers(roleId: string, userIds: string[]): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${roleId}/unassign`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userIds }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to remove role: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取角色用户列表
  async getRoleUsers(roleId: string): Promise<ApiResponse<any[]>> {
    const response = await fetch(`${this.baseUrl}/${roleId}/users`);
    if (!response.ok) {
      throw new Error(`Failed to fetch role users: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 复制角色
  async copyRole(id: string, name: string): Promise<ApiResponse<Role>> {
    const response = await fetch(`${this.baseUrl}/${id}/copy`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to copy role: ${response.statusText}`);
    }
    
    return response.json();
  }
}

// 导出服务实例
export const roleService = new RoleService();